package com.xoa.service.enterpriseWeChat;

import com.xoa.controller.login.loginController;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.enterpriseWeChat.EnterpriseWeChatMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.dingdingManage.*;
import com.xoa.model.enterpriseWeChat.*;
import com.xoa.model.users.Users;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dingding.DingDingTool;
import com.xoa.util.enterpriseWeChat.EnterpriseWeChatRecode;
import com.xoa.util.enterpriseWeChat.EnterpriseWeChatUrl;
import net.sf.json.JsonConfig;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import java.util.Map;
import java.util.HashMap;

/**
 * Created by 桂静文 on 2018/3/22.
 * 企业微信企业号
 */
@Service
public class EnterpriseWeChatService {


        @Autowired
        SysParaMapper sysParaMapper;

        @Autowired
        DepartmentMapper departmentMapper;

        @Autowired
        UsersMapper usersMapper;

        @Autowired
        EnterpriseWeChatMapper enterpriseWeChatMapper;

        @Autowired
        loginController login;

        String accessToken;

        List<EnterpriseWeChatUpdateDept> enterpriseWeChatUpdateDepts = new ArrayList<>();

        List<EnterpriseWeChatUpdateDept> enterpriseWeChatUpdateDepts1 = new ArrayList<>();
        //部门层级
        Integer n = 0;

        //设置企业微信基础参数
        public BaseWrapper baseEnterpriseWeChatSetting(String oaUrl, String corpId, String corpSecret) {
            BaseWrapper wrapper = new BaseWrapper();
            SysPara webSite = sysParaMapper.querySysPara("WECHATQY_OAURL");
            SysPara id = sysParaMapper.querySysPara("WECHATQY_CORPID");
            SysPara secret = sysParaMapper.querySysPara("WECHATQY_SECRET");

            try {
                if (webSite != null) {
                    webSite.setParaValue(oaUrl);
                    sysParaMapper.updateSysPara(webSite);
                } else {
                    webSite = new SysPara();
                    webSite.setParaName("WECHATQY_OAURL");
                    webSite.setParaValue(oaUrl);
                    sysParaMapper.insertSysPara(webSite);
                }

                if (id != null) {
                    id.setParaValue(corpId);
                    sysParaMapper.updateSysPara(id);
                } else {
                    id = new SysPara();
                    id.setParaName("WECHATQY_CORPID");
                    id.setParaValue(corpId);
                    sysParaMapper.insertSysPara(id);
                }

                if (secret != null) {
                    secret.setParaValue(corpSecret);
                    sysParaMapper.updateSysPara(secret);
                } else {
                    secret = new SysPara();
                    secret.setParaName("WECHATQY_SECRET");
                    secret.setParaValue(corpSecret);
                    sysParaMapper.insertSysPara(secret);
                }

                wrapper.setMsg("保存成功！");
                wrapper.setFlag(true);
            } catch (Exception e) {
                e.printStackTrace();
                wrapper.setMsg(e.getMessage());
                wrapper.setFlag(false);
                throw new RuntimeException("保存出错！");
            }
            return wrapper;
        }

        //获取企业微信基础参数
        public BaseWrapper baseEnterpriseWeChatGet() {
            BaseWrapper wrapper = new BaseWrapper();
            List<String> item = new ArrayList<>();
            item.add("WECHATQY_OAURL");
            item.add("WECHATQY_CORPID");
            item.add("WECHATQY_SECRET");

            List<SysPara> sysParaList = sysParaMapper.getSysParaList(item);
            if(sysParaList != null) {
                wrapper.setMsg("查询成功！");
                wrapper.setFlag(true);
                wrapper.setData(sysParaList);

            } else {
                wrapper.setMsg("查询失败！");
            }
            return wrapper;
        }

        //企业微信连接测试
        public void enterpriseWeChatConnect(HttpServletResponse response, String dingUrl, String dingRequest) throws JSONException {
            String result = DingDingTool.dingdingRequestGet(dingUrl, dingRequest);
            JSONObject resultJSON = new JSONObject(result);
            if(resultJSON.getString("errmsg").equals("ok")) {
                accessToken = "?access_token=" + resultJSON.getString("access_token");
            }
            try {
                ServletOutputStream out = response.getOutputStream();
                OutputStreamWriter ow = new OutputStreamWriter(out);
                ow.write(result);
                ow.flush();
                ow.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //获取oa部门列表
        public BaseWrapper enterpriseWeChatGetDeptList(Integer deptId) {
            BaseWrapper wrapper = new BaseWrapper();

            List<Department> enterpriseWeChatDeptList = departmentMapper.getChDept(deptId);
            if(enterpriseWeChatDeptList != null) {
                wrapper.setFlag(true);
                wrapper.setMsg("查询成功！");
                wrapper.setData(enterpriseWeChatDeptList);
            } else {
                wrapper.setMsg("查询失败！");
            }
            return wrapper;
        }

        //获取部门用户列表
        public ToJson<Department> enterpriseWeChatGetUserList(Integer deptId) {
            ToJson<Department> toJson = new ToJson<>();
            try {
                List<Department> deptList = departmentMapper.getChDept(deptId);
                List<Users> usersList = usersMapper.getUsersByDeptId(deptId);
                toJson.setObj(deptList);
                toJson.setObject(usersList);

                toJson.setMsg("OK");
                toJson.setFlag(0);
            } catch (Exception e) {
                e.printStackTrace();
                toJson.setMsg(e.getMessage());
            }
            return toJson;
        }

        //TODO 企业微信组织结构增量同步     返回值不是汉字，需要根据返回码自己写返回数据
        public BaseWrapper enterpriseWeChatDeptSynchro() throws JSONException {
            BaseWrapper wrapper = new BaseWrapper();
            List<EnterpriseWeChatUpdateDept> updateDept = new ArrayList<>();
            List<Long> deleteDept = new ArrayList<>();

            EnterpriseWeChatCreateDept enterpriseWeChatCreateDept;
            EnterpriseWeChatUpdateDept enterpriseWeChatUpdateDept;

            Integer updateResult = 0;
            Integer deleteResult = 0;

            List<Department> deptList = departmentMapper.getDatagrid();

            String dingdingResult = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DEPT_LIST, accessToken);
            if(getErrcode(dingdingResult)!=0) {
                wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(dingdingResult)));
                return wrapper;
            }
            JSONObject jsonObject = new JSONObject(dingdingResult);
            JSONArray jsonArray = jsonObject.getJSONArray("department");

           //创建或更新部门
            for(Department department: deptList) {
                boolean create = true;
                boolean update = true;
                enterpriseWeChatCreateDept = new EnterpriseWeChatCreateDept();
                enterpriseWeChatUpdateDept = new EnterpriseWeChatUpdateDept();
                Integer parentid = departmentMapper.getParentEnterpriseWeChatId(department.getDeptId());
                for(int i = 1; i < jsonArray.length(); i ++) {
                    if(jsonArray.getJSONObject(i).getString("id").equals(department.getWeixinDeptId())) {
                        create = false;
                        if((parentid == null||jsonArray.getJSONObject(i).getInt("parentid") == parentid)
                                &&jsonArray.getJSONObject(i).getString("name").equals(department.getDeptName())) {
                            update = false;
                            break;
                        }
                    } else if(jsonArray.getJSONObject(i).getString("name").equals(department.getDeptName())) {
                        department.setWeixinDeptId(jsonArray.getJSONObject(i).getString("id"));
                        departmentMapper.editDept(department);
                        create = false;
                    }
                }
                if(create) {
                    enterpriseWeChatCreateDept.setName(department.getDeptName());
                    if(department.getDeptParent()==0) {
                        enterpriseWeChatCreateDept.setParentid(1 + "");
                    } else {
                        enterpriseWeChatCreateDept.setParentid(parentid + "");
                    }
                    //bean转换为JSONObject
                    net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(enterpriseWeChatCreateDept);
                    String postData = jsonObj.toString();
                    //创建部门，获取返回的id
                    String result = DingDingTool.dingdingRequestPost(EnterpriseWeChatUrl.WECHAT_CREATE_DEPT, accessToken, postData);
                    if(!getErrcode(result).equals("ok")) {
                        wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(dingdingResult)));
                        return wrapper;
                    }
                    JSONObject resultJSON = new JSONObject(result);
                    String enterpriseWeChatDeptId = resultJSON.getString("id");
                    //写入企业微信部门id
                    department.setWeixinDeptId(enterpriseWeChatDeptId);
                    departmentMapper.editDept(department);
                } else if(update) {
                    enterpriseWeChatUpdateDept.setName(department.getDeptName());
                    enterpriseWeChatUpdateDept.setId(Long.parseLong(department.getWeixinDeptId()));
                    enterpriseWeChatUpdateDept.setParentid(parentid + "");
                    updateDept.add(enterpriseWeChatUpdateDept);
                }
            }

//           //删除部门
//            for(int i = 1; i < jsonArray.length(); i ++) {
//                boolean delete = true;
//                for(Department department: deptList) {
//                    if(jsonArray.getJSONObject(i).getInt("id") == department.getWeixinDeptId()) {
//                        delete = false;
//                        break;
//                    }
//                }
//                if(delete) {
//                    deleteDept.add(jsonArray.getJSONObject(i).getLong("id"));
//                }
//            }

            //发送更新部门请求
            for(EnterpriseWeChatUpdateDept sendUpdateDept: updateDept) {
                //bean转换为JSONObject
                net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(sendUpdateDept);
                String postData = jsonObj.toString();

                String result = DingDingTool.dingdingRequestPost(EnterpriseWeChatUrl.WECHAT_UPDATE_DEPT, accessToken, postData);
                updateResult = getErrcode(result);
                if(updateResult!=0) {
                    break;
                }
            }

            //TODO 发送删除部门请求      无法删除有子部门的部门，需要加判断
//            for(Long id: deleteDept) {
//                String deleteRequest = accessToken + "&id=" + id;
//                String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DELETE_DEPT, deleteRequest);
//                deleteResult = getErrmsg(result);
//                if(!deleteResult.equals("deleted")) {
//                    break;
//                }
//            }

            if(updateResult==0&&deleteResult==0) {
                wrapper.setFlag(true);
                wrapper.setMsg("同步成功！");
            } else {
                wrapper.setMsg("更新操作结果：" + EnterpriseWeChatRecode.getErrorRecode(updateResult) + "！<br>删除操作结果：" + EnterpriseWeChatRecode.getErrorRecode(deleteResult) + "！");
            }
            return wrapper;
        }

        public BaseWrapper enterpriseWeChatDeptSynchroAll(HttpServletRequest request, HttpServletResponse response) {
            BaseWrapper wrapper = new BaseWrapper();
            List<Department> departments = departmentMapper.getAllDepartment();
            //导出
            try {
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("department_table", 12);
                String[] secondTitles = {"部门名称", "部门ID","父部门ID"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"deptName","deptId","deptParent"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, departments, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = null;
                out = response.getOutputStream();
                String filename = "department_table.csv"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }



            return wrapper;
        }

        //企业微信用户管理同步
        public BaseWrapper enterpriseWeChatUserSynchro(String synchroUsers) throws JSONException {
            BaseWrapper wrapper = new BaseWrapper();
            EnterpriseWeChatUser enterpriseWeChatUser;
            List<Integer> enterpriseWeChatDeptList;
            Integer createResult = 0;
            Integer updateResult = 0;
            Integer successNum = 0;
            Integer failedNum = 0;
            String failedReason = "";

            String dingUrl;
            String dingRequest;
            synchroUsers = dealUserSynchroStr(synchroUsers);

            //第一次按部门分开
            for(String deptUsers: synchroUsers.split(";")) {

                //第二次将部门和人员分开
                String dept = deptUsers.split(":")[0];
                String users = deptUsers.split(":")[1];

                Integer enterpriseWeChatDeptId = departmentMapper.getEnterpriseWeChatIdByDeptId(Integer.parseInt(dept));

                if(enterpriseWeChatDeptId==0) {
                    wrapper.setMsg("选中人员所在部门未同步到企业微信，请先同步组织结构！");
                    return wrapper;
                }

                dingRequest = accessToken + "&department_id=" + enterpriseWeChatDeptId;
                dingUrl = EnterpriseWeChatUrl.WECHAT_USER_LIST;
                //查询企业微信中该部门下的所有人员
                String dingdingResponse = DingDingTool.dingdingRequestGet(dingUrl, dingRequest);
                if(getErrcode(dingdingResponse)!=0) {
                    wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(dingdingResponse)));
                    return wrapper;
                }

                JSONObject jsonObject = new JSONObject(dingdingResponse);
                JSONArray jsonArray = jsonObject.getJSONArray("userlist");

                //第三次将人员分开
                for(String user: users.split(",")) {
                    Users theUser = usersMapper.getUserByUid(Integer.parseInt(user));
                    enterpriseWeChatUser = new EnterpriseWeChatUser();
                    enterpriseWeChatDeptList = new ArrayList<>();
                    String result = "";
                    EnterpriseWeChat enterpriseWeChat = new EnterpriseWeChat();
                    enterpriseWeChat.setOaUid(theUser.getUid() + "");

                    //创建更新人员
                    enterpriseWeChatDeptList.add(enterpriseWeChatDeptId);
                    enterpriseWeChatUser.setUserid(theUser.getByname());
                    enterpriseWeChatUser.setDepartment(enterpriseWeChatDeptList);
                    enterpriseWeChatUser.setEmail(theUser.getEmail());
                    enterpriseWeChatUser.setMobile(theUser.getMobilNo());
                    enterpriseWeChatUser.setName(theUser.getUserName());
                    enterpriseWeChatUser.setPosition(theUser.getPost());
                    net.sf.json.JSONObject sendJSONObject = net.sf.json.JSONObject.fromObject(enterpriseWeChatUser);
                    String sendMsg = sendJSONObject.toString();

                    if(enterpriseWeChatUser.getName()==null||"".equals(enterpriseWeChatUser.getName())
                            ||enterpriseWeChatUser.getMobile()==null||"".equals(enterpriseWeChatUser.getMobile())) {
                        failedNum ++;
                        if(!failedReason.contains("、人员未设置电话号码")){
                            failedReason += "、人员未设置电话号码";
                        }
                        continue;
                    }

                    if(jsonArray.length() > 0) {
                        for(int i = 0; i < jsonArray.length(); i ++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            //userId相同，说明存在
                            if(theUser.getUserId().equals(jsonObject1.getString("userid"))) {
                                //如果有一个信息不相同，则更新。
                                if(!jsonObject1.getString("name").equals(theUser.getUserName())||
                                        !jsonObject1.getString("mobile").equals(theUser.getMobilNo())||
                                        !jsonObject1.getString("position").equals(theUser.getPost())||
                                        !jsonObject1.getString("email").equals(theUser.getEmail())||
                                        enterpriseWeChatDeptId!=jsonObject1.getJSONArray("department").getInt(0)){

                                    dingUrl = EnterpriseWeChatUrl.WECHAT_UPDATE_USER;
                                    result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                                    updateResult = getErrcode(result);
                                }
                                enterpriseWeChat.setWxUid(enterpriseWeChatUser.getUserid());
                            } else {
                                dingUrl = EnterpriseWeChatUrl.WECHAT_CREATE_USER;
                                result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                                createResult = getErrcode(result);
                                JSONObject jsonObject2 = new JSONObject(result);
                                enterpriseWeChat.setWxUid(enterpriseWeChatUser.getUserid());
                            }
                        }
                    } else {
                        dingUrl = EnterpriseWeChatUrl.WECHAT_CREATE_USER;
                        result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                        createResult = getErrcode(result);
                        enterpriseWeChat.setWxUid(enterpriseWeChatUser.getUserid());
                    }
                    if(createResult!=0||updateResult!=0) {
                        failedNum ++;
                        if(!failedReason.contains("、" + EnterpriseWeChatRecode.getErrorRecode(getErrcode(result)))) {
                            failedReason += "、" + EnterpriseWeChatRecode.getErrorRecode(getErrcode(result));
                        }
                    } else {
                        successNum ++;
                        if(enterpriseWeChatMapper.getBindBoolean(theUser.getUid()) == 0) {
                            enterpriseWeChatMapper.insert(enterpriseWeChat);
                        }
                    }
                }
            }

            if(failedReason.contains("、")) {
                failedReason = failedReason.replaceFirst("、", "");
                failedReason += "。";
            }
            String result = "成功：" + successNum + "个，失败：" + failedNum + "个";
            if(failedNum > 0) {
                result += "，失败原因：" + failedReason;
            }
            wrapper.setMsg(result);
            wrapper.setFlag(true);
            return wrapper;
        }

      //获取企业微信人员列表
        public BaseWrapper getEnterpriseWeChatUserList() throws JSONException {
            BaseWrapper wrapper = new BaseWrapper();
            List<EnterpriseWeChatBindUser> enterpriseWeChatBindUserList = new ArrayList<>();

            //根据部门查出所有人员
            String dingUrl = EnterpriseWeChatUrl.WECHAT_USER_SIMPLE_LIST;
            String dingRequest = accessToken + "&department_id=1&fetch_child=1";
            JSONObject theDeptsUsers = new JSONObject(DingDingTool.dingdingRequestGet(dingUrl, dingRequest));

            if(!theDeptsUsers.getString("errmsg").equals("ok")) {
                wrapper.setMsg(theDeptsUsers.getString("errmsg"));
                return wrapper;
            }
            JSONArray userList = theDeptsUsers.getJSONArray("userlist");

            if(userList.length() > 0) {
                for(int j = 0; j < userList.length(); j ++) {
                    JSONObject jsonObject1 = userList.getJSONObject(j);
                    EnterpriseWeChatBindUser enterpriseWeChatBindUser = new EnterpriseWeChatBindUser();
                    enterpriseWeChatBindUser.setName(jsonObject1.getString("name"));
                    enterpriseWeChatBindUser.setUserid(jsonObject1.getString("userid"));
                    //查询绑定状态
                    EnterpriseWeChat enterpriseWeChat = enterpriseWeChatMapper.getUserWXMapByUserId(enterpriseWeChatBindUser.getUserid());
                    if(enterpriseWeChat != null) {
                        enterpriseWeChatBindUser.setBind(true);
                    }
                    enterpriseWeChatBindUserList.add(enterpriseWeChatBindUser);
                }
            }

            wrapper.setFlag(true);
            wrapper.setMsg("查询成功");
            wrapper.setData(enterpriseWeChatBindUserList);
            return wrapper;
        }

        //企业微信账号与OA账号绑定与解除绑定，type为0：绑定，type为1：解除绑定
        @Transactional(rollbackFor = RuntimeException.class)
        public BaseWrapper bindEnterpriseWeChatAndOA(String dingdingId, String uid, Integer type) {
            BaseWrapper wrapper = new BaseWrapper();
            EnterpriseWeChat enterpriseWeChat = new EnterpriseWeChat();
            EnterpriseWeChatExample example = new EnterpriseWeChatExample();
            Integer result;
            try {
                if(type == 0) {
                    Integer uuid = Integer.parseInt(uid.split(",")[0]);
                    Users users = usersMapper.getUsersByUid(uuid);
                    if(users.getMobilNo()==null||"".equals(users.getMobilNo())) {
                        wrapper.setMsg("选中人员无电话号码，无法绑定！");
                        return wrapper;
                    }else {
                        if (enterpriseWeChatMapper.getBindBoolean(uuid) == 0) {
                            enterpriseWeChat.setWxUid(dingdingId);
                            enterpriseWeChat.setOaUid(uuid + "");
                            result = enterpriseWeChatMapper.insertSelective(enterpriseWeChat);
                        } else {
                            wrapper.setMsg("该人员已绑定其他企业微信账号，请重新选择！");
                            return wrapper;
                        }
                    }
                } else {
                    example.or().andWxUidEqualTo(dingdingId);
                    result = enterpriseWeChatMapper.deleteByExample(example);
                }

                if(result > 0) {
                    wrapper.setFlag(true);
                    wrapper.setMsg("操作成功！");
                } else {
                    wrapper.setMsg("操作失败！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                wrapper.setMsg(e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
            return wrapper;
        }

        //获取企业微信应用
        public BaseWrapper getEnterpriseWeChatApp(String appName) {
            BaseWrapper wrapper = new BaseWrapper();
            String appUrl = "";
            SysPara sysPara = sysParaMapper.querySysPara(appName);
            EnterpriseWeChatApp enterpriseWeChatApp = new EnterpriseWeChatApp();

            switch (appName){
                case "WECHATQY_APP_XOA": appUrl = EnterpriseWeChatUrl.WECHATQY_APP_XOA;
                    break;
            }
            enterpriseWeChatApp.setEnterpriseWeChatAppId(sysPara.getParaValue());
            enterpriseWeChatApp.setEnterpriseWeChatAppUrl(appUrl);

            if(enterpriseWeChatApp != null) {
                wrapper.setFlag(true);
                wrapper.setMsg("查询成功！");
                wrapper.setData(enterpriseWeChatApp);
            } else {
                wrapper.setMsg("查询失败！");
            }
            return wrapper;
        }

        //企业微信应用设置
        @Transactional(rollbackFor = RuntimeException.class)
        public BaseWrapper enterpriseWeChatAppSetting(String appName, String appId) {
            BaseWrapper wrapper = new BaseWrapper();

            SysPara sysPara = new SysPara();
            sysPara.setParaName(appName);
            sysPara.setParaValue(appId);
            try {
                sysParaMapper.updateSysPara(sysPara);
                wrapper.setFlag(true);
                wrapper.setMsg("保存成功！");
            } catch (Exception e) {
                e.printStackTrace();
                wrapper.setMsg(e.getMessage());
                throw new RuntimeException("保存出错！");
            }
            return wrapper;
        }

        //企业微信组织架构管理获取部门列表
        public void enterpriseWeChatDepSettingGet(HttpServletResponse response, Integer deptId) {
            String dingRequest = accessToken + "&fetch_child=false" + "&id=" + deptId;
            String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DEPT_LIST, dingRequest);
            try {
                ServletOutputStream out = response.getOutputStream();
                OutputStreamWriter ow = new OutputStreamWriter(out, "utf-8");
                ow.getEncoding();
                ow.write(result);
                ow.flush();
                ow.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //TODO 企业微信组织架构管理获取编辑页面下拉菜单    微信提供的接口旧方法不适用，需重新设计
        public BaseWrapper enterpriseWeChatDepSettingMenu() {
            BaseWrapper wrapper = new BaseWrapper();
            enterpriseWeChatUpdateDepts = new ArrayList<>();
//            enterpriseWeChatUpdateDepts1 = new ArrayList<>();

            String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DEPT_LIST, accessToken);
            try {
                if(getErrcode(result)!=0) {
                    wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(result)));
                    return wrapper;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
            net.sf.json.JSONArray jsonArray = jsonObject.getJSONArray("department");

            enterpriseWeChatUpdateDepts = (List<EnterpriseWeChatUpdateDept>) net.sf.json.JSONArray.toList(jsonArray, new EnterpriseWeChatUpdateDept(), new JsonConfig());
//            enterpriseWeChatUpdateDept.setParentid(0 + "");
//            enterpriseWeChatUpdateDepts1.add(enterpriseWeChatUpdateDept);
//            getMenu(1);

            if(enterpriseWeChatUpdateDepts.size() != 0) {
                wrapper.setFlag(true);
                wrapper.setMsg("获取成功！");
                wrapper.setData(enterpriseWeChatUpdateDepts);
            }
            return wrapper;
        }

        //企业微信组织架构管理编辑部门
        public BaseWrapper enterpriseWeChatDepSettingEdit(EnterpriseWeChatUpdateDept enterpriseWeChatUpdateDept) {
            BaseWrapper wrapper = new BaseWrapper();
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(enterpriseWeChatUpdateDept);
            String postData = jsonObject.toString();
            String result = DingDingTool.dingdingRequestPost(EnterpriseWeChatUrl.WECHAT_UPDATE_DEPT, accessToken, postData);
            try {
                if(getErrcode(result)==0) {
                    wrapper.setFlag(true);
                    wrapper.setMsg("更新成功！");
                } else {
                    wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(result)));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                wrapper.setMsg(e.getMessage());
            }
            return wrapper;
        }

        //企业微信组织架构管理删除部门
        public BaseWrapper enterpriseWeChatDepSettingDelete(Integer deptId) {
            BaseWrapper wrapper = new BaseWrapper();
            String dingRequest = accessToken + "&id=" + deptId;
            String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DELETE_DEPT, dingRequest);
            try {
                if(getErrcode(result)==0) {
                    wrapper.setFlag(true);
                    wrapper.setMsg("删除成功！");
                } else {
                    wrapper.setMsg(EnterpriseWeChatRecode.getErrorRecode(getErrcode(result)));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                wrapper.setMsg(e.getMessage());
            }
            return wrapper;
        }

       //TODO 企业微信微应用免登码获取用户身份      后边做
        public BaseWrapper enterpriseWeChatCodeGetUser(HttpServletRequest request, HttpServletResponse response,
                                               String corpId, String corpSecret, String code, String oId) throws JSONException {
            BaseWrapper wrapper = new BaseWrapper();
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);

            if(user.getUserId() == null) {
                String dingRequest = "?corpid=" + corpId + "&corpsecret=" + corpSecret;

                //获取access_token
                String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_CONNECT_TEST, dingRequest);
                JSONObject jsonObject = new JSONObject(result);
                String access = jsonObject.getString("access_token");

                //获取用户id
                dingRequest = "?access_token=" + access + "&code=" + code;
                result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_CODE_GETUSER, dingRequest);
                jsonObject = new JSONObject(result);
                String userid = jsonObject.getString("userid");
                //获取该用户对应的OAId
                String oaId = enterpriseWeChatMapper.getUserWXMapByUserId(userid).getOaUid();
                if("".equals(oaId)||oaId == null) {
                    wrapper.setMsg("用户" + userid + "未绑定OA账号！");
                    return wrapper;
                }

                user = usersMapper.getUserByUid(Integer.parseInt(oaId));
                if(user != null) {
                    try {
//                    ToJson<Users> toJson = login.loginEnter(user.getByname(), user.getPassword(), oId, "mobile", null, request, response);
                        ToJson<Users> toJson = login.loginEnter(user.getByname(), "", oId, "mobile", null, request, response, 1);
                        if(!toJson.isFlag()) {
                            wrapper.setMsg("登录失败！");
                            return wrapper;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        wrapper.setMsg(e.getMessage());
                    }
                    wrapper.setData(SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId));
                    wrapper.setFlag(true);
                    wrapper.setMsg("success!");
                } else {
                    wrapper.setMsg("用户" + oaId + "不存在！");
                }
            } else {
                wrapper.setMsg("已有用户信息！");
                wrapper.setFlag(true);
            }
            return wrapper;
        }


        //工具方法

        //获取接口的返回消息
        public Integer getErrcode(String result) throws JSONException {
            JSONObject jsonObject = new JSONObject(result);
            return jsonObject.getInt("errcode");
        }

        //用户管理同步前端数据处理
        public String dealUserSynchroStr(String synchroUsers) {
            String result = ",";
            Integer deptId = 0;

            for(String one: synchroUsers.split(";")) {
                Integer nowDeptId = Integer.parseInt(one.split(",")[0]);
                String uid = one.split(",")[1];

                if (deptId == nowDeptId) {
                    result += uid + ",";
                } else {
                    result = result.substring(0, result.length() - 1);
                    result += ";" + nowDeptId + ":" + uid + ",";
                    deptId = nowDeptId;
                }
            }
            result = result.replaceFirst(";", "");
            result = result.substring(0, result.length() - 1);
            return result;
        }

        //递归获取下拉菜单
        public void getMenu(long id) {
            String dingRequest = accessToken + "&fetch_child=false" + "&id=" + id;
            String result = DingDingTool.dingdingRequestGet(EnterpriseWeChatUrl.WECHAT_DEPT_LIST, dingRequest);
            n ++;
            try {
                if(getErrcode(result)!=0) {
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                    net.sf.json.JSONArray jsonArray = jsonObject.getJSONArray("department");
                    if(!jsonArray.isEmpty()) {
                        enterpriseWeChatUpdateDepts = jsonArray.toList(jsonArray, new EnterpriseWeChatUpdateDept(), new JsonConfig());
                        for(EnterpriseWeChatUpdateDept enterpriseWeChatUpdateDept: enterpriseWeChatUpdateDepts) {
                            enterpriseWeChatUpdateDept.setParentid(n+"");
                            enterpriseWeChatUpdateDepts1.add(enterpriseWeChatUpdateDept);
                            getMenu(enterpriseWeChatUpdateDept.getId());
                        }
                    }
                }
                n --;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

}
